package org.qfbl.nio.groupChat;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * 群聊服务端
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private int port = 6667;

    public GroupChatServer() {
        try {
            // 1、创建select
            selector = Selector.open();
            // 2.打开serversocketchannel，一个select对应一个serverSocketChannel，同时对应多个socketChannel，socketChannel负责数据的读写
            listenChannel = ServerSocketChannel.open();
            InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
            listenChannel.socket().bind(inetSocketAddress);
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {

            e.printStackTrace();
//            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
        server.listen();
    }

    private void listen() {
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        //如果selectKey是可连接状态的话，需要处理  ，监听到accept
                        if (selectionKey.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println("主机：" + sc.getRemoteAddress() + " 上线");
                        }
                        //如果通道发生read事件，通道可读事件
                        if (selectionKey.isReadable()) {
                            this.readDate(selectionKey);
                        }
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待连接中。。。");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 读取客户端消息,群聊，并转发其他客户端发送消息
    private void readDate(SelectionKey selectionKey) {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) selectionKey.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if (count > 0) {
                String message = new String(buffer.array()).trim();
                System.out.println("from 客户端：" + message);
                // 向其他客户端转发消息
                this.sendInfoToOther(message, channel);
            }


        } catch (Exception e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                //取消注册
                selectionKey.cancel();
                //关闭通道
                channel.close();
            }catch (IOException e2) {
                e2.printStackTrace();;
            }
        }

    }

    /**
     * 转发消息到其他客户端
     *
     * @param message
     * @param channel
     */
    private void sendInfoToOther(String message, SocketChannel channel) {
        System.out.println("转发消息中");
        for (SelectionKey key : selector.keys()) {
            SelectableChannel targetChannel = key.channel();
            // 排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != channel) {
                try {
                    SocketChannel dest = (SocketChannel) targetChannel;
                    dest.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
                    dest.write(buffer);
                } catch (IOException e) {
                    try {
                        System.out.println(channel.getRemoteAddress() + "离线了");
                        //关闭通道
                        key.cancel();
                        channel.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }

                    e.printStackTrace();
                }
            }
        }

    }


}
